package com.cby.jetpack.sample.result

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import com.bumptech.glide.Glide
import com.cby.jetpack.sample.R
import com.cby.jetpack.sample.ext.showToast
import com.cby.util.lib.util.CbyLogUtils

/**
 * @description: SimpleResultActivity
 *
 * @author ChenBaoyang
 * @date 8/5/21 09:27
 */
class SimpleResultActivity : AppCompatActivity() {

    private lateinit var showIv: ImageView
    private lateinit var activityResultLauncher: ActivityResultLauncher<String>

    companion object{
        private const val REQUEST_CODE_ALBUM = 1001
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_result_simple)
        showIv = findViewById(R.id.iv_show)
    }

    override fun onStart() {
        super.onStart()
        //registerForActivityResult 这个必须调用在生命周期start或者之前
        activityResultLauncher = registerForActivityResult(ActivityResultContracts.GetContent()) {
            loadUri(it)
        }
    }

    /**
     * 原始的方式（startActivityForResult），请求相册
     */
    fun onExample1(view: View) {
        val intent = Intent()
        intent.type = "application/pdf"
        intent.action = "android.intent.action.GET_CONTENT"
        intent.addCategory("android.intent.category.OPENABLE")
        startActivityForResult(intent, REQUEST_CODE_ALBUM)
    }



    fun onExample2(view: View) {
        activityResultLauncher.launch("image/*")
    }

    fun onExample3(view: View) {

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_OK) {
            when (requestCode) {
                REQUEST_CODE_ALBUM -> {
                    val uri: Uri? = data?.data
                    showToast(uri.toString())
                    CbyLogUtils.flog("-----Uri-----$uri")
                    //loadUri(uri)
                }
            }
        }
    }

    /**
     * 加载图片
     *
     * @param uri Uri
     */
    private fun loadUri(uri: Uri?) {
        Glide.with(this@SimpleResultActivity).load(uri).into(showIv)
    }
}